I have a 3 byte unsigned char array that contains a length value (someone else's control block) and I need to move the value to my int field.
I tried different flavors of casting, but couldn't come up with a method that didn't ring compiler bells or worked. I ended up using a union, but I am wondering if there is a simpler/better/more proper method.
Code:
#include <stdio.h>
union MyUnion {
char ctemp[4] ;
int itemp ;
} ;
int main(void) {
union MyUnion myunion ;
myunion.itemp = 0 ;
unsigned char c_len[3] = {0,0,5} ;
for (int i = 0 ; i < 3 ; i++ ) printf("c_len[%d]=%d\n", i, c_len[i]) ;
for (int i = 1 ; i < 4 ; i++ ) myunion.ctemp[i] = c_len[i-1] ;
printf("myunion.itemp = %d\n", myunion.itemp) ;
return 0 ;
}
Output:
Code:
c_len[0]=0
c_len[1]=0
c_len[2]=5
myunion.itemp = 5